package z.frpc;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;


import frpclib.Frpclib;


public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        popup("启动中……");

        var handler = new Handler(getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                var s = msg.getData().getString("s");
                if (!TextUtils.isEmpty(s)) {
                    popup(s);
                    stopSelf();
                }
            }
        };


        var s = """
[common]
server_addr = xajysj.com
server_port = 47000

[ssh]
type = tcp
local_ip = 127.0.0.1
local_port = 5900
remote_port = 45900

[ssh2]
type = tcp
local_ip = 127.0.0.1
local_port = 2222
remote_port = 42222
                """;

        new Thread() {
            @Override
            public void run() {
                var bundle = new Bundle();
                bundle.putString("s", Frpclib.runContent("1", s));
                var message = new Message();
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }.start();

        var b = new Notification.Builder(this);
        b.setContentIntent(PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0));
        b.setAutoCancel(false);
        b.setContentText("frpc");
        startForeground(1, b.build());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    private void popup(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }
}